package com.m3839.sdk.common.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Description:AppUtils
 *
 * @author chenbaoyang
 * @create 2020/8/3 16:43
 */
public class AppUtils {

    public final static String SHA1 = "SHA1";

    /**
     * 返回一个签名的对应类型的Sha1字符串
     */
    public static String getSignInfo(Context context) {
        String packageName = context.getApplicationContext().getPackageName();
        Signature[] signs = getSignatures(context, packageName);
        String sha1 = getSignatureString(signs[0], SHA1);
        return sha1;
    }

    /**
     * 返回对应包的签名信息
     */
    public static Signature[] getSignatures(Context context, String packageName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager()
                    .getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            return packageInfo.signatures;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取相应的类型的字符串（把签名的byte[]信息转换成16进制）
     */
    public static String getSignatureString(Signature sig, String type) {
        byte[] hexBytes = sig.toByteArray();
        String fingerprint = "error!";
        try {
            MessageDigest digest = MessageDigest.getInstance(type);
            if (digest != null) {
                byte[] digestBytes = digest.digest(hexBytes);
                StringBuilder sb = new StringBuilder();
                for (byte digestByte : digestBytes) {
                    sb.append((Integer.toHexString((digestByte & 0xFF) | 0x100)).substring(1, 3));
                }
                fingerprint = sb.toString();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return fingerprint;
    }

    /**
     * 用来判断当前的activity是否是不存在，是否被销毁
     *
     * @param activity
     * @return
     */
    public static boolean isValidActivity(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
                return false;
            }
        } else {
            if (activity == null || activity.isFinishing()) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检测是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean isWeChatAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取当前应用的版本号（versionCode）
     *
     * @param context
     * @return
     */
    public static long getAppVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return info.getLongVersionCode();
            } else {
                return info.versionCode;
            }
        } catch (Exception var3) {
            return -1;
        } catch (NoSuchMethodError e) {
            return -1;
        }
    }

    /**
     * 获取某个指定包名的应用的VersionName
     */
    public static String getVersionName(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            return info.versionName;
        } catch (Exception var3) {
            return "";
        }
    }

    /**
     * 判断某个指定包名的应用版本是否大于某个版本
     */
    @Deprecated
    public static boolean checkVersion(Context context, String packageName, String limitVersionName) {
        String hykbAppVersion = AppUtils.getVersionName(context, packageName);
        if (!TextUtils.isEmpty(hykbAppVersion)) {
            return hykbAppVersion.compareTo(limitVersionName) >= 0;
        }
        return false;
    }

    /**
     * 判断某个指定包名的应用的版本号（VersionCode）
     *
     * @param context
     * @return
     */
    public static long getVersionCode(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return info.getLongVersionCode();
            } else {
                return info.versionCode;
            }
        } catch (Exception var3) {
            return -1;
        } catch (NoSuchMethodError e) {
            return -1;
        }
    }

    /**
     * 判断指定包名的版本号是否大于某个版本
     *
     * @param context
     * @param limitVersionCode 界限版本，指要大于的某个版本
     * @return
     */
    public static boolean checkVersionCode(Context context, String packageName, long limitVersionCode) {
        long versionCode = AppUtils.getVersionCode(context, packageName);
        return versionCode >= limitVersionCode;
    }


    /**
     * 打开一个链接
     *
     * @param context
     * @param url
     */
    public static void openUrl(Context context, String url) {
        if(TextUtils.isEmpty(url)) {
            return;
        }
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        if (context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            context.startActivity(intent);
        } else {
            //找不到指定的activity
        }
    }

    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * 杀进程
     * @param activity
     */
    public static void killAllProcess(Activity activity){
        if(activity == null) {
            return;
        }
        Context context = activity.getApplicationContext();
        activity.finish();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> mList = mActivityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : mList) {
            if (runningAppProcessInfo.pid != android.os.Process.myPid()) {
                android.os.Process.killProcess(runningAppProcessInfo.pid);
            }
        }

    }

    public static boolean isInvalidActivity(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
                return true;
            }
        }else {
            if (activity == null || activity.isFinishing()) {
                return true;
            }
        }
        return false;
    }
}
